'use strict';
const db = uniCloud.database()
exports.main = async (event, context) => {
	try {
		const clinic_data = {
			userId: event.userId,
			clinic: event.data.clinic,
			addressProvince: event.data.addressProvince,
			addressCity: event.data.addressCity,
			addressCounty: event.data.addressCounty,
			address: event.data.address,
			integral: 50,
			delete: 0
		}
		
		// 创建诊所
		const res_clinic = await db.collection('rx-clinic').add(clinic_data)
		
		// 用户与类型与诊所关联
		const res_users_clinic = await db.collection('rx-users-clinic').where({ userId: event.userId, types: event.types }).get()
		const clinic_list = res_users_clinic.data[0].clinic
		clinic_list.push(res_clinic.id)
		await db.collection('rx-users-clinic').doc(res_users_clinic.data[0]._id).update({ clinic: clinic_list })
		clinic_data._id = res_users_clinic.data[0]._id
		
		//返回数据给客户端
		return { data: clinic_data, code: 200, msg: 'ok.' }
	} catch (err) {
		console.log(err)
		return { data: {}, code: 201, msg: '服务端错误.' }
	}
};
